﻿var map = null;
var shapeLayer;
var lineLayer;
var polyPoints = new Array();
var down = 0;
var X = 0, Y = 0;
var origin;
var MaxLat = 0;
var MinLat = 0;
var MaxLon = 0;
var MinLon = 0;
var map;
var VElonlatArray = new Array();
var zipCodeArray = new Array();
var teeritory = new Array();
var menuLayer = null;
var assignmentName = null;
var lastAssignID = null;
var types = null;
var AssignIndex = null; //the assignment dropdownlist's selectIndex   
var AssignName = null; //the assignment dropdownlist's selectText   
window.onload = function create_map() {
    hideHeaderDiv();
    if (window.screen.width == 1024) {
        document.getElementById("myMap1").className = "divAt1024";
    }
    else if (window.screen.width == 1280) {
        document.getElementById("myMap1").className = "divAt1280";
    }
    else {
        document.getElementById("myMap1").className = "divOthers";
    }
    PageMethods.IsPurchased(CallBackIsPurchased);
    map = new VEMap('myMap1');
    map.LoadMap();
    shapeLayer = new VEShapeLayer();
    map.AddShapeLayer(shapeLayer);
    map.EnableShapeDisplayThreshold(false);
    lineLayer = new VEShapeLayer();
    map.AttachEvent("onmouseup", MouseUpHandler);
    map.AttachEvent("onmousedown", MouseDownHandler);
    map.AttachEvent("onmousemove", MouseMoveHandler);
    PageMethods.GetAssignName(callBackAssign);
    PageMethods.Pin(CallBack);
    map.AddShapeLayer(lineLayer);
   // map.SetZoomLevel(7);
}

function hideHeaderDiv() {
    var current = document.getElementById("header");
    current.parentNode.removeChild(current);
    current = document.getElementById("topsection");
    current.parentNode.removeChild(current);
    current = document.getElementById("breadcrumb");
    current.parentNode.removeChild(current);
}

function CallBack(result) {
    var serial = Sys.Serialization.JavaScriptSerializer;
    var info = serial.deserialize(result);
    AssignIndex = document.getElementById("ctl00_DetailsContent_drpAssignment").selectedIndex;
    AssignName = document.getElementById("ctl00_DetailsContent_drpAssignment").options[AssignIndex].text;
    AssignName = AssignName.replace(/(^\s*)|(\s*$)/g, "");

    if (info.length > 0) {
        MaxLat = info[0].Latitude;
        MinLat = info[0].Latitude;
        MaxLon = info[0].Longitude;
        MinLon = info[0].Longitude;
    }

    for (var i in info) {
        types = document.getElementById("viewTypes").selectedIndex;
        if (types == 0 || types == 2 || types == 1) {
            AddPushpin(info[i].Latitude, info[i].Longitude, info[i].LeadBlockCode, info[i].ZipName, info[i].City, info[i].Territory, info[i].ActiveLeadCount, info[i].LapsedLeadCount, info[i].NeighborLeadCount, info[i].BusinessLeadCount, info[i].IsOrdered, info[i].UserAssigned, info[i].ZipId);
        }
        if (types == 3 && info[i].UserAssigned != null) {
            AddPushpin(info[i].Latitude, info[i].Longitude, info[i].LeadBlockCode, info[i].ZipName, info[i].City, info[i].Territory, info[i].ActiveLeadCount, info[i].LapsedLeadCount, info[i].NeighborLeadCount, info[i].BusinessLeadCount, info[i].IsOrdered, info[i].UserAssigned, info[i].ZipId);
        }
        if (types == 4 && info[i].UserAssigned == null) {
            AddPushpin(info[i].Latitude, info[i].Longitude, info[i].LeadBlockCode, info[i].ZipName, info[i].City, info[i].Territory, info[i].ActiveLeadCount, info[i].LapsedLeadCount, info[i].NeighborLeadCount, info[i].BusinessLeadCount, info[i].IsOrdered, info[i].UserAssigned, info[i].ZipId);
        }
        UpdateLatLon(info[i].Latitude, info[i].Longitude);
    }
    var lat = (parseFloat(MaxLat) + parseFloat(MinLat)) / 2.0;
    var lon = (parseFloat(MaxLon) + parseFloat(MinLon)) / 2.0;
    var velatlon = new VELatLong(lat, lon);
    map.SetCenterAndZoom(velatlon,7);
}

function CallBackZipCodes(result) {
    var serial = Sys.Serialization.JavaScriptSerializer;
    var info = serial.deserialize(result);
    if (info.length > 0) {
        MaxLat = info[0].Latitude;
        MinLat = info[0].Latitude;
        MaxLon = info[0].Longitude;
        MinLon = info[0].Longitude;
    }
    for (var i in info) {
        AddPushpinZipCodes(info[i].Latitude, info[i].Longitude, info[i].ZipName, info[i].Territory, info[i].ActiveLeadCount, info[i].LapsedLeadCount, info[i].NeighborLeadCount, info[i].BusinessLeadCount, info[i].UserId, info[i].IsOrdered);
        UpdateLatLon(info[i].Latitude, info[i].Longitude);
    }
    IsNeedPostback = true;
    var lat = (parseFloat(MaxLat) + parseFloat(MinLat)) / 2.0;
    var lon = (parseFloat(MaxLon) + parseFloat(MinLon)) / 2.0;
    var velatlon = new VELatLong(lat, lon);
    map.SetCenter(velatlon);
}

function CallBackLeads(result) {
    var serial = Sys.Serialization.JavaScriptSerializer;
    var info = serial.deserialize(result);
    if (info.length > 0) {
        MaxLat = info[0].Latitude;
        MinLat = info[0].Latitude;
        MaxLon = info[0].Longitude;
        MinLon = info[0].Longitude;
    }

    for (var i in info) {
        AddPushpinLeads(info[i].LeadId, info[i].SelPersonId, info[i].Zip, info[i].LeadBlockCode, info[i].Division, info[i].Market, info[i].Territory, info[i].CallType, info[i].LeadType, info[i].MdNumber, info[i].BirthDate, info[i].SequenceNumber, info[i].County, info[i].State, info[i].City, info[i].RawData, info[i].FirmName, info[i].LastName, info[i].FirstName, info[i].StreetAddress, info[i].LeadCity, info[i].LeadState, info[i].Telephone, info[i].SubSequenceNumber, info[i].Latitude, info[i].Longitude, info[i].SelDNC, info[i].PcLeadType, info[i].DncAfterDate, info[i].UserId);
        UpdateLatLon(info[i].Latitude, info[i].Longitude);
    }
    IsNeedPostback = true;
    var lat = (parseFloat(MaxLat) + parseFloat(MinLat)) / 2.0;
    var lon = (parseFloat(MaxLon) + parseFloat(MinLon)) / 2.0;
    var velatlon = new VELatLong(lat, lon);
    map.SetCenter(velatlon);
}

function CallBackIsPurchased(result) {
    //    if(!result)
    //    {
    //     alert('You have not placed an order yet. You must place your order before creating assignments.');
    //    }
}

function AddPushpinLeads(LeadId, SelPersonId, Zip, LeadBlockCode, Division, Market, Territory, CallType, LeadType, MdNumber, BirthDate, SequenceNumber, County, State, City, RawData, FirmName, LastName, FirstName, StreetAddress, LeadCity, LeadState, Telephone, SubSequenceNumber, Latitude, Longitude, SelDNC, PcLeadType, DncAfterDate, UserId) {
    var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(Latitude, Longitude));
    shapeLayer.AddShape(shape);
    var info = "Zip+4:" + Zip + "<br>" + "LeadBlockCode:" + LeadBlockCode + "<br>" + "Division:" + Division + "<br>" + "Market:" + Market + "<br>" + "Territory:" + Territory + "<br>" + "CallType:" + CallType + "<br>" + "LeadType:" + LeadType + "<br>" + "BirthDate:" + BirthDate + "<br>" + "SequenceNumber:" + SequenceNumber + "<br>" + "FirmName:" + FirmName + "<br>" + "LastName:" + LastName + "<br>" + "FirstName:" + FirstName + "<br>" + "StreetAddress:" + StreetAddress + "<br>" + "City:" + LeadCity + "<br>" + "State:" + LeadState + "<br>" + "Telephone:" + Telephone + "<br>" + "SelDNC:" + SelDNC + "<br>" + "DncAfterDate:" + DncAfterDate + "<br>";
    addActiveLeads(LeadType, Territory, UserId);
    shape.SetCustomIcon(" <img src='../Content/Images/pin3.gif'/> ");
    shape.SetDescription(info);
}


function AddPushpinZipCodes(x, y, ZipName, teer, active, lasped, neighbor, business, UserId, IsOrdered) {
    var lat = x;
    var lon = y;
    var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, lon));
    shapeLayer.AddShape(shape);
    if (UserId != null) {
        UserId = UserId.replace(/(^\s*)|(\s*$)/g, "");
    }
    var info = '<br>Zip Name:' + ZipName + '<br>Territory: ' + teer + '<br>Active Count: ' + active + '<br>Lasped Count:' + lasped + '<br>Neighbor Count: ' + neighbor + '<br>Business Count: ' + business + '<br>';
    // addActive(active,lasped,neighbor,business,teer,UserAssigned);
    addActiveFirst(active, lasped, neighbor, business, teer, UserId);
    var assign = assignmentName;
    if (UserId != null) {
        assign = assignmentName.substring(0, assignmentName.indexOf(UserId) - 1) + ' selected="selected"' + assignmentName.substring(assignmentName.indexOf(UserId) - 1);
        shape.SetDescription(info + '<br>Assign to:<select id="selectAssign" onchange="assignZips(' + ZipName + ',selectAssign.options[selectAssign.selectedIndex].value,selectAssign.options[selectAssign.selectedIndex].text,1)">' + assign + '</select><br><a href="#" onclick="clearAssign(' + ZipName + ',1)">Clear assignment</a>');
        shape.SetCustomIcon(" <img src='../Content/Images/pin10.gif'/> ");
    }
    else {
        shape.SetDescription(info + '<br>Assign to:<select id="selectAssign" onchange="assignZips(' + ZipName + ',selectAssign.options[selectAssign.selectedIndex].value,selectAssign.options[selectAssign.selectedIndex].text,1)">' + assign + '</select>');
        shape.SetCustomIcon(" <img src='../Content/Images/pin1.gif'/> ");
    }
    shape.SetMoreInfoURL(ZipName + "|" + IsOrdered + "|" + teer + "|" + shape.GetCustomIcon() + "|" + active + "|" + lasped + "|" + neighbor + "|" + business + "|" + UserId);
    if (AssignIndex != 0 && AssignName != UserId) {
        shape.Hide();
    }
}

function AddPushpin(x, y, leadBlock, zipCode, city, teer, active, lasped, neighbor, business, IsOrder, UserAssigned, ZipId) {
    if (UserAssigned != null) {
        UserAssigned = UserAssigned.replace(/(^\s*)|(\s*$)/g, "");
    }
    var lat = x;
    var lon = y;
    var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, lon));
    shapeLayer.AddShape(shape);
    var info = 'Lead Block: ' + leadBlock + '<br>Zip Code:' + zipCode + '<br>City: ' + city + '<br>Territory: ' + teer + '<br>Active Count: ' + active + '<br>Lasped Count:' + lasped + '<br>Neighbor Count: ' + neighbor + '<br>Business Count: ' + business + '<br>';
    addActiveFirst(active, lasped, neighbor, business, teer, UserAssigned);
    var assign = assignmentName;
    var mailerWeek = '<br>Mailer week:&nbsp;&nbsp;&nbsp;&nbsp;<select name="SelectMailer1" id="SelectMailer1" onchange="ChangeWeek(' + ZipId + ',selectAssign.options[selectAssign.selectedIndex].text,SelectMailer1.options[SelectMailer1.selectedIndex].text);"><option value="A" >1</option><option value="B">2</option><option value="C">3</option><option value="D">4</option><option value="5">5</option></select><br>';
    if (UserAssigned != null) {
            var CurMailerWeek = UserAssigned.substring(0, UserAssigned.indexOf(' '));
            var UserAssigned = UserAssigned.substring(UserAssigned.indexOf(' ') + 1);
            mailerWeek = mailerWeek.substring(0, mailerWeek.indexOf('>' + CurMailerWeek + '<')) + ' selected="selected"' + mailerWeek.substring(mailerWeek.indexOf('>' + CurMailerWeek + '<'));

            assign = assignmentName.substring(0, assignmentName.indexOf('>' + UserAssigned + '<')) + ' selected="selected"' + assignmentName.substring(assignmentName.indexOf('>' + UserAssigned + '<'));
            shape.SetDescription(info + mailerWeek + '<br>Assign to:<select id="selectAssign" onchange="assignZips(' + ZipId + ',selectAssign.options[selectAssign.selectedIndex].value,selectAssign.options[selectAssign.selectedIndex].text,SelectMailer1.options[SelectMailer1.selectedIndex].text,0)">' + assign + '</select><br><a href="#" onclick="clearAssign(' + ZipId + ',0)">Clear assignment</a>');
            shape.SetCustomIcon(" <img src='../Content/Images/pin10.gif'/> ");     
    }
    else {
        shape.SetDescription(info + mailerWeek + '<br>Assign to:<select id="selectAssign" onchange="assignZips(' + ZipId + ',selectAssign.options[selectAssign.selectedIndex].value,selectAssign.options[selectAssign.selectedIndex].text,SelectMailer1.options[SelectMailer1.selectedIndex].text,0)">' + assign + '</select>');
        shape.SetCustomIcon(" <img src='../Content/Images/pin1.gif'/> ");
    }
    shape.SetMoreInfoURL(ZipId + "|" + IsOrder + "|" + teer + "|" + shape.GetCustomIcon() + "|" + active + "|" + lasped + "|" + neighbor + "|" + business + "|" + UserAssigned);
    if (AssignIndex != 0 && AssignName != UserAssigned) {
        shape.Hide();
    }
}



function MouseUpHandler(e) {
    if (e.leftMouseButton) {
        // alert('ok');
        if (down == 1) {
            down = 0;
            polyPoints.push(origin);
            polygonDescrption();
            X = 0;
            Y = 0;
        }
        else {
            var menuLayer1 = document.getElementById('divPolygon');
            if (menuLayer != null) {
                menuLayer1.style.visibility = 'hidden';
                lineLayer.DeleteAllShapes();
                menuLayer = null;
            }
        }

    }
}

function MouseDownHandler(e) {
    if (e.rightMouseButton) {
        X = e.mapX;
        Y = e.mapY;

        var point = map.PixelToLatLong(new VEPixel(X, Y));

        if (down == 0) {
            //intialize the map and variables.                       
            lineLayer.DeleteAllShapes();
            if (menuLayer != null) {
                var menuLayer1 = document.getElementById('divPolygon');
                menuLayer1.style.visibility = 'hidden';
                menuLayer = null;
            }
            polyPoints = new Array(0);
            origin = point;
            polyPoints.push(origin);
            down = 1;
        }

        //add the new point to the array
        polyPoints.push(point);
        menuKey = true;
        return true;
    }
}

function MouseMoveHandler(e) {
    if (down == 1) {
        var x = e.mapX;
        var y = e.mapY;

        var dx = Math.abs(X) - Math.abs(x);
        var dy = Math.abs(Y) - Math.abs(y);

        //do not want to redraw polygon unless we move a significant amount
        if (Math.abs(dx) > 5 || Math.abs(dy) > 5) {
            var latlong = map.PixelToLatLong(new VEPixel(x, y));
            polyPoints.pop();
            polyPoints.push(latlong);
            drawPolygon();
        }
    }
}

function drawPolygon() {
    //remove the polygon that is on the map
    lineLayer.DeleteAllShapes();

    //draw polyline if there is only two points in the array
    if (polyPoints.length < 3) {
        var polygon = new VEShape(VEShapeType.Polyline, polyPoints);
    }
    else {
        //create a new polygon
        var polygon = new VEShape(VEShapeType.Polygon, polyPoints);
    }
    polygon.SetZIndex(shapeLayer.GetShapeCount() + 99);
    polygon.HideIcon();

    //draw the new polygon on the map
    lineLayer.AddShape(polygon);
}



function polygonSearch() {
    var counter = 0;
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        var latlong = shape.GetPoints()[0];
        var lat = latlong.Latitude;
        var lon = latlong.Longitude;
        var str = new Array();
        if (pointInPolygon(polyPoints, lat, lon)) {
            str = shape.GetMoreInfoURL().split('|');

        }
    }
}

function pointInPolygon(points, lat, lon) {
    var i;
    var j = points.length - 1;
    var inPoly = false;

    for (i = 0; i < points.length; i++) {

        if (points[i].Longitude < lon && points[j].Longitude >= lon || points[j].Longitude < lon && points[i].Longitude >= lon) {
            if (points[i].Latitude + (lon - points[i].Longitude) / (points[j].Longitude - points[i].Longitude) * (points[j].Latitude - points[i].Latitude) < lat) {
                inPoly = !inPoly;
            }
        }
        j = i;
    }

    return inPoly;
}
function addActiveFirst(A, L, N, B, Teer, UserAssign) {
    var lbneighbor = document.getElementById("ctl00_InfoContent_lbNeighborLead");
    var lbactive = document.getElementById("ctl00_InfoContent_lbActiveLead");
    var lbbussiness = document.getElementById("ctl00_InfoContent_lbBussinessLead");
    var lblapse = document.getElementById("ctl00_InfoContent_lbLapseLead");
    var lbneighborAssign = document.getElementById("ctl00_InfoContent_lbNeighborLeadAssign");
    var lbactiveAssign = document.getElementById("ctl00_InfoContent_lbActiveLeadAssign");
    var lbbussinessAssign = document.getElementById("ctl00_InfoContent_lbBussinessLeadAssign");
    var lblapseAssign = document.getElementById("ctl00_InfoContent_lbLapseLeadAssign");
    var lbneighborUnAssign = document.getElementById("ctl00_InfoContent_lblNeighborUnAssign");
    var lbactiveUnAssign = document.getElementById("ctl00_InfoContent_lblActiveUnAssign");
    var lbbussinessUnAssign = document.getElementById("ctl00_InfoContent_lblBussinessUnAssign");
    var lblapseUnAssign = document.getElementById("ctl00_InfoContent_lblLapsedUnAssign");
    var lblAssign = document.getElementById("ctl00_InfoContent_lblAassign");
    var lblUnAssign = document.getElementById("ctl00_InfoContent_lblUnAssign");
    lbactive.innerHTML = parseInt(lbactive.innerHTML) + parseInt(A);
    lbbussiness.innerHTML = parseInt(lbbussiness.innerHTML) + parseInt(B);
    lblapse.innerHTML = parseInt(lblapse.innerHTML) + parseInt(L);
    lbneighbor.innerHTML = parseInt(lbneighbor.innerHTML) + parseInt(N);
    if (UserAssign != 'null' && UserAssign != null) {
        lbactiveAssign.innerHTML = parseInt(lbactiveAssign.innerHTML) + parseInt(A);
        lbbussinessAssign.innerHTML = parseInt(lbbussinessAssign.innerHTML) + parseInt(B);
        lblapseAssign.innerHTML = parseInt(lblapseAssign.innerHTML) + parseInt(L);
        lbneighborAssign.innerHTML = parseInt(lbneighborAssign.innerHTML) + parseInt(N);
        lblAssign.innerHTML = parseInt(lblAssign.innerHTML) + 1;
    }
    else {
        lbactiveUnAssign.innerHTML = parseInt(lbactiveUnAssign.innerHTML) + parseInt(A);
        lbbussinessUnAssign.innerHTML = parseInt(lbbussinessUnAssign.innerHTML) + parseInt(B);
        lblapseUnAssign.innerHTML = parseInt(lblapseUnAssign.innerHTML) + parseInt(L);
        lbneighborUnAssign.innerHTML = parseInt(lbneighborUnAssign.innerHTML) + parseInt(N);
        lblUnAssign.innerHTML = parseInt(lblUnAssign.innerHTML) + 1;

    }
}

function addActiveLeads(LeadType, Teer, UserId) {
    var lbneighbor = document.getElementById("ctl00_InfoContent_lbNeighborLead");
    var lbactive = document.getElementById("ctl00_InfoContent_lbActiveLead");
    var lbbussiness = document.getElementById("ctl00_InfoContent_lbBussinessLead");
    var lblapse = document.getElementById("ctl00_InfoContent_lbLapseLead");
    var lbneighborAssign = document.getElementById("ctl00_InfoContent_lbNeighborLeadAssign");
    var lbactiveAssign = document.getElementById("ctl00_InfoContent_lbActiveLeadAssign");
    var lbbussinessAssign = document.getElementById("ctl00_InfoContent_lbBussinessLeadAssign");
    var lblapseAssign = document.getElementById("ctl00_InfoContent_lbLapseLeadAssign");
    var lbneighborUnAssign = document.getElementById("ctl00_InfoContent_lblNeighborUnAssign");
    var lbactiveUnAssign = document.getElementById("ctl00_InfoContent_lblActiveUnAssign");
    var lbbussinessUnAssign = document.getElementById("ctl00_InfoContent_lblBussinessUnAssign");
    var lblapseUnAssign = document.getElementById("ctl00_InfoContent_lblLapsedUnAssign");
    var lblAssign = document.getElementById("ctl00_InfoContent_lblAassign");
    var lblUnAssign = document.getElementById("ctl00_InfoContent_lblUnAssign");
    switch (LeadType) {
        case "A":
            lbactive.innerHTML = parseInt(lbactive.innerHTML) + 1;
            if (UserId != null) {
                lbactiveAssign.innerHTML = parseInt(lbactiveAssign.innerHTML) + 1;
                lblAssign.innerHTML = parseInt(lblAssign.innerHTML) + 1;
            }
            else {
                lblapseUnAssign.innerHTML = parseInt(lbactiveUnAssign.innerHTML) + 1;
                lblUnAssign.innerHTML = parseInt(lblUnAssign.innerHTML) + 1;
            }
            break;
        case "L":
            lblapse.innerHTML = parseInt(lblapse.innerHTML) + 1;
            if (UserId != null) {
                lblapseAssign.innerHTML = parseInt(lblapseAssign.innerHTML) + 1;
                lblAssign.innerHTML = parseInt(lblAssign.innerHTML) + 1;
            }
            else {
                lblapseUnAssign.innerHTML = parseInt(lblapseUnAssign.innerHTML) + 1;
                lblUnAssign.innerHTML = parseInt(lblUnAssign.innerHTML) + 1;
            }
            break;
        case "N":
            lbneighbor.innerHTML = parseInt(lbneighbor.innerHTML) + 1;
            if (UserId != null) {
                lbneighborAssign.innerHTML = parseInt(lbneighborAssign.innerHTML) + 1;
                lblAssign.innerHTML = parseInt(lblAssign.innerHTML) + 1;
            }
            else {
                lbneighborUnAssign.innerHTML = parseInt(lbneighborUnAssign.innerHTML) + 1;
                lblUnAssign.innerHTML = parseInt(lblUnAssign.innerHTML) + 1;
            }
            break;
        case "B":
            lbbussiness.innerHTML = parseInt(lbbussiness.innerHTML) + 1;
            if (UserId != null) {
                lbbussinessAssign.innerHTML = parseInt(lbbussinessAssign.innerHTML) + 1;
                lblAssign.innerHTML = parseInt(lblAssign.innerHTML) + 1;
            }
            else {
                lbactiveUnAssign.innerHTML = parseInt(lbactiveUnAssign.innerHTML) + 1;
                lblUnAssign.innerHTML = parseInt(lblUnAssign.innerHTML) + 1;
            }
            break;
    }
}

function addActive(A, L, N, B, Teer, UserAssign) {

    var lbneighborAssign = document.getElementById("ctl00_InfoContent_lbNeighborLeadAssign");
    var lbactiveAssign = document.getElementById("ctl00_InfoContent_lbActiveLeadAssign");
    var lbbussinessAssign = document.getElementById("ctl00_InfoContent_lbBussinessLeadAssign");
    var lblapseAssign = document.getElementById("ctl00_InfoContent_lbLapseLeadAssign");
    var lbneighborUnAssign = document.getElementById("ctl00_InfoContent_lblNeighborUnAssign");
    var lbactiveUnAssign = document.getElementById("ctl00_InfoContent_lblActiveUnAssign");
    var lbbussinessUnAssign = document.getElementById("ctl00_InfoContent_lblBussinessUnAssign");
    var lblapseUnAssign = document.getElementById("ctl00_InfoContent_lblLapsedUnAssign");
    var lblAssign = document.getElementById("ctl00_InfoContent_lblAassign");
    var lblUnAssign = document.getElementById("ctl00_InfoContent_lblUnAssign");
   
    if (UserAssign != 'null' && UserAssign != null) {
        lbactiveAssign.innerHTML = parseInt(lbactiveAssign.innerHTML) + parseInt(A);
        lbbussinessAssign.innerHTML = parseInt(lbbussinessAssign.innerHTML) + parseInt(B);
        lblapseAssign.innerHTML = parseInt(lblapseAssign.innerHTML) + parseInt(L);
        lbneighborAssign.innerHTML = parseInt(lbneighborAssign.innerHTML) + parseInt(N);
        lblAssign.innerHTML = parseInt(lblAssign.innerHTML) + 1;

        lbactiveUnAssign.innerHTML = parseInt(lbactiveUnAssign.innerHTML) - parseInt(A);
        lbbussinessUnAssign.innerHTML = parseInt(lbbussinessUnAssign.innerHTML) - parseInt(B);
        lblapseUnAssign.innerHTML = parseInt(lblapseUnAssign.innerHTML) - parseInt(L);
        lbneighborUnAssign.innerHTML = parseInt(lbneighborUnAssign.innerHTML) - parseInt(N);
        lblUnAssign.innerHTML = parseInt(lblUnAssign.innerHTML) - 1;
    }
}

function SubActive(A, L, N, B, Teer, UserAssign) {
   
    var lbneighborAssign = document.getElementById("ctl00_InfoContent_lbNeighborLeadAssign");
    var lbactiveAssign = document.getElementById("ctl00_InfoContent_lbActiveLeadAssign");
    var lbbussinessAssign = document.getElementById("ctl00_InfoContent_lbBussinessLeadAssign");
    var lblapseAssign = document.getElementById("ctl00_InfoContent_lbLapseLeadAssign");
    var lbneighborUnAssign = document.getElementById("ctl00_InfoContent_lblNeighborUnAssign");
    var lbactiveUnAssign = document.getElementById("ctl00_InfoContent_lblActiveUnAssign");
    var lbbussinessUnAssign = document.getElementById("ctl00_InfoContent_lblBussinessUnAssign");
    var lblapseUnAssign = document.getElementById("ctl00_InfoContent_lblLapsedUnAssign");
    var lblAssign = document.getElementById("ctl00_InfoContent_lblAassign");
    var lblUnAssign = document.getElementById("ctl00_InfoContent_lblUnAssign");
   
    lbactiveUnAssign.innerHTML = parseInt(lbactiveUnAssign.innerHTML) + parseInt(A);
    lbbussinessUnAssign.innerHTML = parseInt(lbbussinessUnAssign.innerHTML) + parseInt(B);
    lblapseUnAssign.innerHTML = parseInt(lblapseUnAssign.innerHTML) + parseInt(L);
    lbneighborUnAssign.innerHTML = parseInt(lbneighborUnAssign.innerHTML) + parseInt(N);
    lblUnAssign.innerHTML = parseInt(lblUnAssign.innerHTML) + 1;

    lbactiveAssign.innerHTML = parseInt(lbactiveAssign.innerHTML) - parseInt(A);
    lbbussinessAssign.innerHTML = parseInt(lbbussinessAssign.innerHTML) - parseInt(B);
    lblapseAssign.innerHTML = parseInt(lblapseAssign.innerHTML) - parseInt(L);
    lbneighborAssign.innerHTML = parseInt(lbneighborAssign.innerHTML) - parseInt(N);
    lblAssign.innerHTML = parseInt(lblAssign.innerHTML) - 1;
}

function ViewAssignByTeer(operateType) {
    var teer;
    var lbneighborAssign = document.getElementById("ctl00_InfoContent_lbNeighborLeadAssign");
    var lbactiveAssign = document.getElementById("ctl00_InfoContent_lbActiveLeadAssign");
    var lbbussinessAssign = document.getElementById("ctl00_InfoContent_lbBussinessLeadAssign");
    var lblapseAssign = document.getElementById("ctl00_InfoContent_lbLapseLeadAssign");
    var lbneighborUnAssign = document.getElementById("ctl00_InfoContent_lblNeighborUnAssign");
    var lbactiveUnAssign = document.getElementById("ctl00_InfoContent_lblActiveUnAssign");
    var lbbussinessUnAssign = document.getElementById("ctl00_InfoContent_lblBussinessUnAssign");
    var lblapseUnAssign = document.getElementById("ctl00_InfoContent_lblLapsedUnAssign");
    var active = 0;
    var bussiness = 0;
    var neigh = 0;
    var lapsed = 0;
    var sum = 0;
    if (operateType == '0') {

        teer = document.getElementById("ctl00_InfoContent_DrpAssign").options[document.getElementById("ctl00_InfoContent_DrpAssign").selectedIndex].value;
        for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
            var shape = shapeLayer.GetShapeByIndex(i);
            var str = new Array();
            str = shape.GetMoreInfoURL().split('|');
            var currentTeer = str[2];
            if (teer == currentTeer || teer == '0000') {
                if (str[8] != 'null') {
                    active += parseInt(str[4]);
                    bussiness += parseInt(str[7]);
                    neigh += parseInt(str[6]);
                    lapsed += parseInt(str[5]);
                }
            }
        }
        lbactiveAssign.innerHTML = active;
        lbbussinessAssign.innerHTML = bussiness;
        lblapseAssign.innerHTML = lapsed;
        lbneighborAssign.innerHTML = neigh;
    }
    else {
        teer = document.getElementById("ctl00_InfoContent_DrpUnAssign").options[document.getElementById("ctl00_InfoContent_DrpUnAssign").selectedIndex].value;
        for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
            var shape = shapeLayer.GetShapeByIndex(i);
            var str = new Array();
            str = shape.GetMoreInfoURL().split('|');
            var currentTeer = str[2];
            if (teer == currentTeer || teer == '0000') {
                if (str[8] == 'null') {
                    active += parseInt(str[4]);
                    bussiness += parseInt(str[7]);
                    neigh += parseInt(str[6]);
                    lapsed += parseInt(str[5]);
                }
            }
        }
        lbactiveUnAssign.innerHTML = active;
        lbbussinessUnAssign.innerHTML = bussiness;
        lblapseUnAssign.innerHTML = lapsed;
        lbneighborUnAssign.innerHTML = neigh;
    }
}

function polygonDescrption() {
    var counter = 0;
    var ordered = 0;
    var unorder = 0;
    var A = 0;
    var L = 0;
    var N = 0;
    var B = 0;
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        var latlong = shape.GetPoints()[0];
        var lat = latlong.Latitude;
        var lon = latlong.Longitude;
        if (pointInPolygon(polyPoints, lat, lon)) {
            var str = new Array();
            str = shape.GetMoreInfoURL().split('|');
            A = A + parseInt(str[4]);
            L = L + parseInt(str[5]);
            N = N + parseInt(str[6]);
            B = B + parseInt(str[7]);
        }
    }
    var mailerWeek = '<br>Mailer week:<br><select name="SelectMailer" id="SelectMailer" onchange=""><option value="0" >Select Week</option><option value="A" >1</option><option value="B">2</option><option value="C">3</option><option value="D">4</option><option value="5">5</option></select><br>';
    var info = "<font size='2px'>&nbsp;Your totals so far are:<br><font color='red'>&nbsp;" + A + "</font> Actived;<br><font color='red'>&nbsp;" + L + "</font> Lapsed;<br><font color='red'>&nbsp;" + N + "</font> Neighbor;" + "<br><font color='red'>&nbsp;" + B + "</font> Business;";
    info += mailerWeek;
    info += '&nbsp;Assign to:<select id="selectAssigns"   onchange="polygonAssignZips(this.options[this.selectedIndex].value,this.options[this.selectedIndex].text,SelectMailer.options[SelectMailer.selectedIndex].text,0); ">' + assignmentName + '</select>';
    info += '<br>&nbsp;<a href="#"   onclick="polygonAssignZips(\'0\',\'0\',\'1\',1)"> Clear assignment</a></font>';

    lineLayer.DeleteAllShapes();
    if (polyPoints.length < 3) {
        var polygon = new VEShape(VEShapeType.Polyline, polyPoints);
    }
    else {
        var polygon = new VEShape(VEShapeType.Polygon, polyPoints);
    }

    var menuLayer1 = document.getElementById('divPolygon');
    menuLayer1.style.visibility = 'visible';
    menuLayer1.style.position = "absolute";
    menuLayer1.style.top = window.event.clientY;
    menuLayer1.style.left = window.event.clientX;
    menuLayer1.style.width = "160px";
    menuLayer1.style.height = "220px";
    menuLayer1.style.zIndex = 1000;
    var contentmenu = document.getElementById('PolyMenuContent');
    contentmenu.innerHTML = info;
    polygon.HideIcon();
    lineLayer.AddShape(polygon);
    menuLayer = true;
}

function createAssign(assignName) {
    if (assignName != '') {
        PageMethods.IsAssignExist(assignName, callBackIsAssignExist);
    }
    else {
        alert("The assignment name can not be empty !");
    }
}

function callBackIsAssignExist(result) {
    var result1 = result.split('|');
    if (result1[0] == '0') {
        PageMethods.addAssign(result1[1], callBackAssignID);
        divmassage_box1.style.visibility = 'hidden';
        divmask1.style.visibility = 'hidden';
        Alert('Assignment Creation', 'You have successfully created the ' + result1[1] + ' assignment. You may now add lead blocks to it.');
    }
    else {
        alert("Create failure,the assignment name already exists.");
    }
}

function callBackAssignID(result) {
    lastAssignID = result;
    var assignName = document.getElementById("Text1").value;
    var tOption = document.createElement("Option");
    tOption.text = assignName;
    tOption.value = lastAssignID;
    document.all("ctl00_DetailsContent_drpAssignment").add(tOption);
    assignmentName += '<option value="' + lastAssignID + '">' + assignName + '</option>';
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        var str = new Array();
        str = shape.GetMoreInfoURL().split('|');
        var assign = assignmentName;
        var info = shape.GetDescription();
        info = info.substring(0, info.lastIndexOf('</select>'));
        info += '<option value="' + lastAssignID + '">' + assignName + '</option>';
        info += shape.GetDescription().substring(shape.GetDescription().lastIndexOf('</select>'));
        shape.SetDescription(info);
    }
    document.getElementById("Text1").value = '';
}

function callBackAssign(result) {
    assignmentName = result;
}

function assignZips(zipId, agentId, agentName,mailerWeek, opearte) {
    if (agentId != '0000') {

        if (agentName != '' && mailerWeek != 'Select Week') {
            PageMethods.AssignZips(zipId, mailerWeek + ' ' +agentName);
        }
        else {
            PageMethods.AssignZips(zipId, agentName);
        }
        for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
            var shape = shapeLayer.GetShapeByIndex(i);
            var str = new Array();
            str = shape.GetMoreInfoURL().split('|');
            if (str[0] == zipId) {
                if (str[8] == 'null') {
                    var desc = shape.GetMoreInfoURL().replace('null', agentName);
                    shape.SetMoreInfoURL(desc);
                    addActive(str[4], str[5], str[6], str[7], str[2], agentId);
                }
                var description = shape.GetDescription();
                description = description.replace('Clear assignment', '');
                description = description.replace('selected="selected"', '');
                description = description.replace('selected="selected"', '');
                description += '<br><a href="#" onclick="clearAssign(' + zipId + ')">Clear assignment</a>';
                description = description.substring(0, description.indexOf("value='" + agentId + "'")) + ' selected="selected"' + description.substring(description.indexOf("value='" + agentId + "'") );
                description = description.substring(0, description.indexOf(">" + mailerWeek+"<")) + ' selected="selected"' + description.substring(description.indexOf(">" + mailerWeek+"<") );
                shape.SetDescription(description);
                shape.SetCustomIcon(" <img src='../Content/Images/pin10.gif'/> ");
            }
        }
    }

}


function ViewleadsByAssignment() {
    if (types == 2) {
        return;
    }
    AssignIndex = document.getElementById("ctl00_DetailsContent_drpAssignment").selectedIndex;
    AssignName = document.getElementById("ctl00_DetailsContent_drpAssignment").options[AssignIndex].text;
    AssignName = AssignName.replace(/(^\s*)|(\s*$)/g, "");
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        var str = new Array();
        str = shape.GetMoreInfoURL().split('|');
        if (str[8] != AssignName && AssignIndex != 0) {
            shape.Hide();
        }
        else {
            shape.Show();
        }
    }

}

function clearAssign(zipId, operate) {
    PageMethods.AssignZips(zipId,null);
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        var str = new Array();
        str = shape.GetMoreInfoURL().split('|');
        if (str[0] == zipId) {
            if (str[8] != 'null') {
                shape.SetMoreInfoURL(shape.GetMoreInfoURL().replace(str[8], 'null'));
                SubActive(str[4], str[5], str[6], str[7], str[2], 'null');
            }
            var description = shape.GetDescription();
            description = description.replace('selected="selected"', '');
            description = description.replace('selected="selected"', '');
            description = description.replace('Clear assignment', '');
            shape.SetDescription(description);
            shape.SetCustomIcon(" <img src='../Content/Images/pin1.gif'/> ");
        }
    }
}

function polygonAssignZips(agentID,agentName,mailerWeek,operate)  //if agentID is 0,then clear assign,others assgin to agenID
{
     if (agentName!= '0' && mailerWeek != 'Select Week') {
                    agentName = mailerWeek + " " + agentName;
                }
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        var latlong = shape.GetPoints()[0];
        var lat = latlong.Latitude;
        var lon = latlong.Longitude;
        if (pointInPolygon(polyPoints, lat, lon)) {
            var str = new Array();
            str = shape.GetMoreInfoURL().split('|');
            if (agentName!= '0') {
                PageMethods.AssignZips(str[0], agentName);
                if (str[8] == 'null') {
                    var desc = shape.GetMoreInfoURL().replace('null', agentID);
                    shape.SetMoreInfoURL(desc);
                    addActive(str[4], str[5], str[6], str[7], str[2], agentID);
                }
                var description = shape.GetDescription();
                description = description.replace('selected="selected"', '');
                description = description.replace('selected="selected"', '');
                description = description.replace('Clear assignment', '');
                description += '<br><a href="#" onclick="clearAssign(' + str[0] + ')">Clear assignment</a>';
                description = description.substring(0, description.indexOf("value='" + agentID + "'")) + ' selected="selected"' + description.substring(description.indexOf("value='" + agentID + "'"));
                description = description.substring(0, description.indexOf(">" + mailerWeek + "<")) + ' selected="selected"' + description.substring(description.indexOf(">" + mailerWeek + "<"));
                shape.SetDescription(description);
                shape.SetCustomIcon(" <img src='../Content/Images/pin10.gif'/> ");
            }
            else {
                PageMethods.AssignZips(str[0], null);
                if (str[8] != 'null') {
                    shape.SetMoreInfoURL(shape.GetMoreInfoURL().replace(str[8], 'null'));
                    SubActive(str[4], str[5], str[6], str[7], str[2], 'null');
                }

                var description = shape.GetDescription();
                description = description.replace('selected="selected"', '');
                description = description.replace('selected="selected"', '');
                description = description.replace('Clear assignment', '');
                shape.SetDescription(description);
                shape.SetCustomIcon(" <img src='../Content/Images/pin1.gif'/> ");
            }
        }
    }
}

function viewByDifferent() {
    shapeLayer.DeleteAllShapes();
    lineLayer.DeleteAllShapes();
    types = document.getElementById("viewTypes").selectedIndex;
    cleartSummary(0);
    map.AttachEvent("onmouseup", MouseUpHandler);
    map.AttachEvent("onmousedown", MouseDownHandler);
    map.AttachEvent("onmousemove", MouseMoveHandler);
    if (types == 2) {
        map.DetachEvent("onmouseup", MouseUpHandler);
        map.DetachEvent("onmousedown", MouseDownHandler);
        map.DetachEvent("onmousemove", MouseMoveHandler);
        PageMethods.GetLeads(CallBackLeads);
    }
    else {
        PageMethods.Pin(CallBack);
    }

}

function unSelectAll() {
    if (types == 2) {
        return;
    }
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        var str = new Array();
        str = shape.GetMoreInfoURL().split('|');
        if (str[8] != 'null') {

            clearAssign(str[0], 0);
        }
    }
    cleartSummary(1);
}

function cleartSummary(operate) {
    var lbneighbor = document.getElementById("ctl00_InfoContent_lbNeighborLead");
    var lbactive = document.getElementById("ctl00_InfoContent_lbActiveLead");
    var lbbussiness = document.getElementById("ctl00_InfoContent_lbBussinessLead");
    var lblapse = document.getElementById("ctl00_InfoContent_lbLapseLead");
    var lbneighborAssign = document.getElementById("ctl00_InfoContent_lbNeighborLeadAssign");
    var lbactiveAssign = document.getElementById("ctl00_InfoContent_lbActiveLeadAssign");
    var lbbussinessAssign = document.getElementById("ctl00_InfoContent_lbBussinessLeadAssign");
    var lblapseAssign = document.getElementById("ctl00_InfoContent_lbLapseLeadAssign");
    var lbneighborUnAssign = document.getElementById("ctl00_InfoContent_lblNeighborUnAssign");
    var lbactiveUnAssign = document.getElementById("ctl00_InfoContent_lblActiveUnAssign");
    var lbbussinessUnAssign = document.getElementById("ctl00_InfoContent_lblBussinessUnAssign");
    var lblapseUnAssign = document.getElementById("ctl00_InfoContent_lblLapsedUnAssign");
    var lblAssign = document.getElementById("ctl00_InfoContent_lblAassign");
    var lblUnAssign = document.getElementById("ctl00_InfoContent_lblUnAssign");

    if (operate == 0) {
        lbactive.innerHTML = '0';
        lblapse.innerHTML = '0';
        lbneighbor.innerHTML = '0';
        lbbussiness.innerHTML = '0';
        lbactiveAssign.innerHTML = '0';
        lblapseAssign.innerHTML = '0';
        lbneighborAssign.innerHTML = '0';
        lbbussinessAssign.innerHTML = '0';
        lbactiveUnAssign.innerHTML = '0';
        lblapseUnAssign.innerHTML = '0';
        lbneighborUnAssign.innerHTML = '0';
        lbbussinessUnAssign.innerHTML = '0';
        lblAssign.innerHTML = '0';
        lblUnAssign.innerHTML = '0';
    }
    else {
        lbactiveUnAssign.innerHTML = parseInt(lbactiveUnAssign.innerHTML) + parseInt(lbactiveAssign.innerHTML);
        lbactiveAssign.innerHTML = '0';
        lbactiveAssign.innerHTML = '0';
        lblapseAssign.innerHTML = '0';
        lbneighborAssign.innerHTML = '0';
        lbbussinessAssign.innerHTML = '0';

        lbactiveUnAssign.innertHTML = lbactive.innerHTML;
        lblapseUnAssign.innerHTML = lblapse.innerHTML;
        lbneighborUnAssign.innerHTML = lbneighbor.innerHTML;
        lbbussinessUnAssign.innerHTML = lbbussiness.innerHTML;
    }
}


function ViewAgent(type) {
    var divMessage = document.getElementById("div_content");
    if (type == 0) {
        divMessage.innerHTML = '<BR><select id="selectAssign1" >' + assignmentName + '</select>';
        divMessage.innerHTML += '<BR><br><input id="Button8" type="button" value="OK"  class="filterbutton" onclick="NewWindow(selectAssign1.options[selectAssign1.selectedIndex].value,0);"/>';
    }
    else {
        divMessage.innerHTML = '<BR><select id="selectAssign1"  >' + assignmentName + '</select>';
        divMessage.innerHTML += '<BR><br><input id="Button8" type="button" value="OK"  class="filterbutton" onclick="NewWindow(selectAssign1.options[selectAssign1.selectedIndex].value,1);"/>';
    }
}

function NewWindow(agentID, type) {
    if (agentID != '0000') {
        var divMessage = document.getElementById("divmassage_box3");
        divMessage.style.visibility = "hidden";
        var divMask = document.getElementById("divmask1");
        divMask.style.visibility = "hidden";
        if (type == 1) {
            var itop = (window.screen.availHeight - 300) / 2;
            var ileft = (window.screen.availWidth - 680) / 2;
            var temp = window.open("AgentRatios.aspx?agentId=" + agentID, '', "width=680,height=300,resizable=yes,top=" + itop + ",left=" + ileft);
        }
        else {
            var itop = (window.screen.availHeight - 500) / 2;
            var ileft = (window.screen.availWidth - 750) / 2;
            var temp = window.open("AgentPotential.aspx?agentId=" + agentID, '', "width=750,height=500,resizable=yes,scrollbars=yes,top=" + itop + ",left=" + ileft);
        }
    }
}

function ViewRatio() {
    var divMessage = document.getElementById("divmassage_box3");
    divMessage.style.visibility = "hidden";
    //divMask.style.visibility="hidden";
    divMessage = document.getElementById("divmassage_box4");
    divMessage.style.visibility = "visible";
    var divTitle = document.getElementById("divtitle");
    divTitle.innerHTML = "Agent ratio";
}
function callBackPotential(result) {
    alert(result);
}

function UpdateLatLon(lat, lon) {
    if (lat > MaxLat) {
        MaxLat = lat;
    }
    else if (lat < MinLat) {
        MinLat = lat;
    }

    if (lon > MaxLon) {
        MaxLon = lon;
    }
    else if (lon < MinLon) {
        MinLon = lon;
    }

}

function Alert(alertTitle, content) {
    var titles = document.getElementById("alertTitle");
    var contents = document.getElementById("showText");
    titles.innerHTML = alertTitle;
    contents.innerHTML = content;
    divmassage_box2.style.visibility = 'visible';
    divmask1.style.visibility = 'visible';
}

function ChangeWeek(zipID, assignName, mailerWeek) {
    if (assignName != 'Select Assignment' && mailerWeek != 'Select Week') {
        assignZips(zipID, 'unkown', assignName, mailerWeek);
    }

}